<script>
export default {
  name: "SelectCountry",
}
</script>

<script setup>
import useCommonStore from "@/store/modules/common"
const commonStore = useCommonStore()
// import { useAttrs } from "vue"
// const attrs = useAttrs()
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  valueKey: {
    type: String,
    default: "id",
  },
  labelKey: {
    type: String,
    default: "name",
  },
  labelKey2: {
    type: String,
    default: "",
  },
  collapseTags: {
    type: Boolean,
    default: false,
  },
  isHandle: {
    type: Boolean,
    default: false,
  },
})

const optionsList = computed(() => {
  if (!commonStore.countryOptions.length) {
    commonStore.getCountryOption()
  }
  let data = commonStore.countryOptions || []
  // console.log(data)
  data = data?.map((v) => ({ ...v, [props.labelKey]: props.labelKey2 ? `${v[props.labelKey]} ${props.labelKey2 ? v.country : ""}` : v[props.labelKey] }))

  return data
})
const emit = defineEmits(["change", "changeLabel", "changeItem", "update:modelValue"])
const handleChange = (val) => {
  // emit("change", val)
  emit("update:modelValue", val)
  const item = optionsList.value?.find((i) => i.id == val)
  if (item) {
    emit("changeLabel", item.country)
    emit("changeItem", item)
  }
}
const handleCheckAll = (item, type = "") => {
  let valueList = getOpt(optionsList.value, filterValue.value)?.map((v) => v[props.valueKey])
  let attrValue = []
  // 全选
  if (type == "all") {
    attrValue = valueList
  }
  // 反选
  if (type == "reversion") {
    if (filterValue.value) {
      attrValue = optionsList.value.filter((v) => !valueList.includes(v[props.valueKey]))?.map((v) => v[props.valueKey])
    } else {
      attrValue = optionsList.value.filter((v) => !props.modelValue.includes(v[props.valueKey]))?.map((v) => v[props.valueKey])
    }
  }
  emit("update:modelValue", attrValue)
}
const filterValue = ref("")
const filterMethodPlatform = (v) => {
  filterValue.value = v
}
const getOpt = (opt = [], val) => {
  return opt?.filter((v) => v[props.labelKey].toLowerCase().includes(val.toLowerCase())) || []
}

defineExpose({
  optionsList,
})
</script>

<template>
  <el-select :modelValue="modelValue" v-bind="$attrs" clearable filterable :collapse-tags="collapseTags" @change="handleChange" class="select-wrap" :filter-method="filterMethodPlatform">
    <div v-if="isHandle" class="select-handle">
      <el-button type="primary" link @click="handleCheckAll(item, 'reversion')">反选</el-button>
      <el-button type="primary" link @click="handleCheckAll(item, 'all')">全选</el-button>
    </div>
    <el-option v-for="item in getOpt(optionsList || [], filterValue)" :key="item.id" :label="item[labelKey]" :value="item[valueKey]" />
  </el-select>
</template>

<style lang="scss" scoped>
.select-handle {
  text-align: right;
  padding: 4px 12px;
}
</style>
